<template>
  <div>
    <el-card shadow="never">
      <header-title title="商户管理"></header-title>
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-col :span="21">
          <div>
            商户信息:
            <el-input v-model="searchName" placeholder="请输入内容" size="small" style="margin-right: 15px;width: 150px;"></el-input>
            营业状态:
            <el-select v-model="status" @change="changeStatus" placeholder="请选择" size="small" style="margin: 0 15px 0 15px;width: 150px;">
              <el-option :key="-1" label="全部" :value="-1"></el-option>
              <el-option :key="1" label="在营" :value="1"></el-option>
              <el-option :key="2" label="休业" :value="2"></el-option>
              <el-option :key="3" label="退租" :value="3"></el-option>
              <el-option :key="4" label="注册" :value="4"></el-option>
            </el-select>
            主营类型:
            <el-select v-model="businessType" @change="changeBusinessType" placeholder="请选择" size="small" style="margin: 0 15px 0 15px;width: 150px;">
              <el-option :key="-1" label="全部" :value="-1"></el-option>
              <el-option v-for="item in businessTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            是否签订合同:
            <el-select v-model="contractState" @change="changeContractState" placeholder="请选择" size="small" style="margin: 0 15px 0 15px;width: 150px;">
              <el-option :key="-1" label="全部" :value="-1"></el-option>
              <el-option :key="0" label="未签订" :value="0"></el-option>
              <el-option :key="1" label="已签订" :value="1"></el-option>
            </el-select>
            <el-button @click="search" class="button" size="small" round icon="el-icon-search" style="margin: 10px 0;">查询</el-button>
          </div>
        </el-col>
        <el-col :span="3">
           <!--<el-button class="button" size="small" round>添加商户</el-button>-->
           <el-button @click="addBusiness" class="button" size="small" round>添加商户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <div>
        <el-table :data="businessData" v-loading="loading" style="width: 100%">
          <el-table-column prop="businessName" label="商户名称"></el-table-column>
          <el-table-column prop="stallName" label="摊位号"></el-table-column>
          <el-table-column prop="personInCharge" label="法人"></el-table-column>
          <el-table-column prop="phone" label="联系方式"></el-table-column>
          <el-table-column prop="contractStateName" label="合同状态"></el-table-column>
          <el-table-column prop="statusName" label="营业状态"></el-table-column>
          <el-table-column prop="businessTypeName" label="主营类型"></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <!--<el-upload class="upload-demo" ref="upAvatar" action="https://upload.qiniup.com"
                style="display: inline-block;"
                :on-remove='handleRemove'
                :on-success="handleSuccess"
                list-type="picture"
                :limit='1'
                :data='uploadToken'
                :before-upload="beforeUpload"
              >
                <el-button type="text" @click="uploadAvatar(scope.row)" style="color:#71dc80;">上传头像</el-button>
              </el-upload>
              <el-upload class="upload-demo" ref="upBusinessLicense" action="https://upload.qiniup.com"
                style="display: inline-block;"
                :on-remove='handleRemove'
                :on-success="handleSuccess"
                list-type="picture"
                :limit='1'
                :data='uploadToken'
                :before-upload="beforeUpload"
              >
                <el-button type="text" @click="uploadBusinessLicense(scope.row)" style="color:#55b7ff;">上传营业执照</el-button>
              </el-upload>-->
              <!-- <el-button @click="uploadAvatar(scope.row)" type="text" style="color:#71dc80;">上传头像</el-button> -->
              <!-- <el-button @click="uploadBusinessLicense(scope.row)" type="text" style="color:#55b7ff;">上传营业执照</el-button> -->
              <!-- <el-button @click="getSerialList(scope.row)" type="text" style="color:#d54af7;">电子秤解绑</el-button>
              <el-tooltip content="点一下就直接退租了噢" placement="top">
                <el-button @click="deleteStall(scope.row)" type="text" style="color:#f7674a;">退租</el-button>
              </el-tooltip> -->
              <el-button @click="businessDetails(scope.row)" type="text" style="color:#3dc2c2;">商户信息</el-button>
              <el-button @click="businessEdit(scope.row)" type="text" style="color:#71dc80;">编辑</el-button>
              <el-button @click="businessDelete(scope.row)" type="text" style="color:#dc1033;">删除</el-button>
              <!-- <el-button @click="healthList(scope.row)" type="text" style="color:#55b7ff;">健康证列表</el-button> -->
              <!--<el-dropdown @command="handleCommand">
                <span class="el-dropdown-link" style="padding-left: 10px;">
                  更多<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a">
                    <el-button @click="getSerialList(scope.row)" type="text" style="color:#d54af7;">电子秤解绑</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item command="b">
                    <el-tooltip content="点一下就直接退租了噢" placement="top">
                      <el-button @click="deleteStall(scope.row)" type="text" style="color:#f7674a;">退租</el-button>
                    </el-tooltip>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>-->
            </template>
          </el-table-column>
          <div slot="empty"><img src="../../assets/blank_tip_page/blank_tip_page.png" alt=""></div>
        </el-table>
        <el-pagination
          :page-size="perPage"
          :current-page="page"
          :total="total"
          @current-change="changeBusinessPage"
          style="margin-top: 15px;"
          background
          layout="prev, pager, next"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog title="填写商户信息" :visible.sync="addDialog" @close="close">
      <div>
        <el-form :model="addModal" label-width="100px">
          <el-form-item label="商户名称：" prop="businessName">
            <el-input v-model="addModal.businessName"></el-input>
          </el-form-item>
          <el-form-item label="摊位名称：" prop="stallName">
            <el-input v-model="addModal.stallName"></el-input>
          </el-form-item>
        </el-form>
        <!-- <el-form-item label="商户名称：" prop="businessName">
          <my-select ref="mySelect" url="api/v1/backend/public/product" @selected='mySelectedSampleName'></my-select>
        </el-form-item> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBusiness">提交商户信息</el-button>
      </div>
    </el-dialog>
    <el-dialog title="商户绑定电子秤列表" :visible.sync="serialDialog" @close="closeSerialDialog">
      <div>
        <el-table
          ref="multipleTable"
          :data="serialData"
          v-loading="loading"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column prop="name" label="电子秤编号"></el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setSerialUnbind">设置电子秤解绑</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="" :visible.sync="infoModal">
      <div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoCancel">取 消</el-button>
        <el-button type="primary" @click="infoOk">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import HeaderTitle from "@/components/HeaderTitle"
import MySelect from "@/components/MySelect"
export default {
  name: 'Business',
  components: {
    HeaderTitle,
    MySelect
  },
  data(){
    return {
      loading: true,
      businessData: [],
      searchName: '',
      status: -1, // 营业状态-1 全部 1:在营,2:修业,3:注销 4.注册 5.待绑卡
      businessType: -1, // 商户经营类型	-1 全部
      businessTypeList: [],
      contractState: -1, // 合同是否已签订	-1 全部 0 未签订 1 已签订
      perPage: 10, // 每页显示10条
      page: 1, // 当前页
      total: 0,
      addDialog: false,
      addModal: {
        businessName: '',
        stallName: '',
      },
      serialDialog: false,
      businessId: 0,
      serialData: [],
      serialNumber: '', // 存勾选的电子秤编号

      businessId: 0,
      type: 1,  // 1.营业执照 2.商户头像
      imgUrl: '',
      uploadToken:{
        key:'',
        token:''
      }
    }
  },
  watch: {
    '$store.state.app.marketId'(val, oldVal){
      this.getBusinessType()
      this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
    }
  },
  mounted(){
    this.goodsToken()
    this.getBusinessType()
    this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
  },
  methods:{
    handleCommand(command) {
      // console.log(command)
      // this.$message('click on item ' + command);
    },
    changeStatus(val){
      this.status = val
    },
    changeBusinessType(type){
      console.log(type)
      this.businessType = type
    },
    changeContractState(type){
      this.contractState = type
    },
    // 获取商户主营类型
    getBusinessType(){
      this.$store.dispatch('equipment/fetchBusinessType').then(
        data => {
          let items = []
          for (let item of data) {
            items.push({
              value: item.id + '',
              label: item.name
            })
          }
          this.businessTypeList = items
        }
      ).catch(err => {
        this.businessTypeList = []
      })
    },
    // 获取商户列表
    getBusinessList(searchName,status,businessType,contractState,perPage,page){
      this.$store.dispatch('business/fetchBusinessList',{searchName,status,businessType,contractState,perPage,page}).then(
        data => {
          this.loading = false
          this.businessData = data.items
          this.total = data.total
        }
      ).catch(err => {
        this.loading = false
        this.businessData = []
        this.total = 0
      })
    },
    search(){
      this.page = 1
      this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
    },
    changeBusinessPage(num){
      this.page = num
      this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, num)
    },
    // 点击填写商户信息
    addBusiness(){
        this.$router.push({
        path: `businessEdit/add`
      })
    },
    close(){
      this.clear()
    },
    clear(){
      this.addModal = {}
    },
    // mySelectedSampleName(obj){
    //   console.log(obj)
    //   this.modal.sampleName = obj.label
    // },
    // 提交商户信息
    submitBusiness(){
      console.log(this.addModal)
      // return
      this.addDialog = false
      this.$store.dispatch("business/fetchBusinessSubmit", this.addModal).then(data=>{
        console.log(data)
        // this.$message({
        //   type: 'success',
        //   message: '操作成功，请刷新！'
        // })
      })
    },
    handleSelectionChange(selection) {
      this.serialNumber = selection[0].name
    },
    getRowKeys(row){
      return row.id
    },
    // 获取电子秤绑定列表
    getSerialList(row){
      this.serialDialog = true
      this.loading = false
      this.businessId = row.businessId
      const businessId = row.businessId
      this.$store.dispatch("business/fetchSerialList", {businessId}).then(data=>{
        let data2 = []
        for(let item of data){
          data2.push({
            id: item.serialId,
            name: item.serialNumber
          })
        }
        this.serialData = data2
      })
    },
    // 设置电子秤解绑
    setSerialUnbind(){
      this.serialDialog = false
      this.$store.dispatch("business/fetchSetSerialUnbind", {businessId: this.businessId,serialNumber: this.serialNumber}).then(data=>{
        if(data.data){
          this.$message({
            type: 'success',
            message: '解绑成功，请刷新页面！'
          })
        }else{
          alert('解绑失败！')
        }
        this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
      })
    },
    // 关闭电子秤解绑弹框
    closeSerialDialog(){
      this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
      this.businessId = 0,
      this.serialNumber = ''
    },
    // 退租
    deleteStall(row){
      const businessId = row.businessId
      this.$store.dispatch("business/fetchDeleteStall", {businessId}).then(data=>{
        if(data.data){
          this.$message({
            type: 'success',
            message: '退租成功，请刷新页面！'
          })
        }
        this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
      })
    },
    // 商户详情
    businessDetails(row){
      const businessId = row.businessId
      const businessName = row.businessName
      this.$router.push({
        path: `businessDetails/${businessId}`,
        query: {
          businessId: businessId,
          businessName: businessName
        }
      })
    },
    // 商户编辑
    businessEdit(row){
      const businessId = row.businessId
//      const a = JSON.stringify(row)
      this.$router.push({
        path: `businessEdit/${businessId}`,
        query: {
          businessId: businessId,
//          a:a
        }
      })
    },

    businessDelete(row){
      const businessId = row.businessId
      this.$confirm(`是否确定要删除商户 "${row.businessName}"`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch("business/fetchBusinessDelete", {businessId}).then(data=>{
          if(data){
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
          }
          this.getBusinessList(this.searchName, this.status, this.businessType, this.contractState, this.perPage, this.page)
        })
      })
    },
    // 健康证列表
    healthList(row){
      console.log(row)
      const businessId = row.businessId
      this.$router.push({
        path: `business/healthList/${businessId}`,
        query: {
          businessId: businessId
        }
      })
    },
    handleSuccess(res, file, fileList){
      this.imgUrl = 'http://cailanzi.image.cailanzi001.com/' + res.key
      this.getUploadImg(this.businessId, this.type, this.imgUrl)
    },
    handleRemove(file, fileList) {
      console.log(file,fileList[0])
    },
    beforeUpload(file){
      const isPNG = file.type === "image/png"
      const isJPEG = file.type === "image/jpeg"
      const isJPG = file.type === "image/jpg"
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!")
        return false
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
        return false
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date()
      this.uploadToken.key=`bill${date.getFullYear()}${date.getMonth()+1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(Math.random()*100)}.${file.type.split('/')[1]}`
    },
    //获取上传文件时候的token
    goodsToken(){
      this.$store.dispatch('purchaseInfo/uptoken',{}).then(
        data => {
          this.uploadToken.token = data.data.uptoken
        }
      ).catch(err => {
      })
    },
    // 上传头像
    uploadAvatar(row){
      this.businessId = row.businessId
      this.type = 2  // 1.营业执照 2.商户头像
    },
    // 上传营业执照
    uploadBusinessLicense(row){
      this.businessId = row.businessId
      this.type = 1  // 1.营业执照 2.商户头像
    },
    getUploadImg(businessId, type, imgUrl){
      this.$store.dispatch("business/fetchBusinessImg", {businessId, type, imgUrl}).then(data=>{
        this.$message({
          type: 'success',
          message: '上传成功，点击商户信息查看图片！'
        })
        this.$refs['upAvatar'].clearFiles()
        this.$refs['upBusinessLicense'].clearFiles()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  /deep/ .el-table__empty-text{
    width: 100%;
  }
  .button {
    background: #64d9d6;
    color: #fff;
    margin-left: 40px;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
